package com.lmx.repoDomain.repository;

import java.util.List;
import java.util.Map;

import javax.annotation.PostConstruct;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.lmx.common.util.CommonUtil;
import com.lmx.persistence.service.HealthInfoService;
import com.lmx.repoDomain.tmodel.HealthInfo;

import io.katharsis.queryParams.QueryParams;
import io.katharsis.repository.annotations.JsonApiFindAll;
import io.katharsis.repository.annotations.JsonApiResourceRepository;

@JsonApiResourceRepository(HealthInfo.class)
@Component
public class HealthInfoRepository extends BaseRepository<HealthInfo> {

	@Autowired
	private HealthInfoService<HealthInfo> healthInfoService;

	@PostConstruct
	public void init() {
		dslJpaService.setEntityClass(HealthInfo.class);
	}

	@Override
	@JsonApiFindAll
	public Iterable<HealthInfo> findAll(final QueryParams requestParams) {
		Map<String, String> keyMap = CommonUtil.getKeyMapByFilter(requestParams);
		String typeValue = keyMap.get("healthInfoQueryType");
		String examUserId = keyMap.get("examUser.id");
		if (StringUtils.isNotBlank(typeValue) && "forType".equals(typeValue)) {
			Long customerId = Long.parseLong(keyMap.get("examUser.id"));
			Integer days = Integer.parseInt(keyMap.get("day"));
			Long itemtypeId = Long.parseLong(keyMap.get("itemtype.id"));
			return this.healthInfoService.findNearDataByType(customerId, days, itemtypeId);
		}
		if (StringUtils.isNotBlank(typeValue) && "forAll".equals(typeValue)) {
			Long customerId = Long.parseLong(keyMap.get("examUser.id"));
			Integer days = Integer.parseInt(keyMap.get("day"));
			return this.healthInfoService.findNearDataAll(customerId, days);
		}
		if (typeValue != null && typeValue.equals("normal")) {
			return super.findAll(requestParams);
		}
		if (typeValue == null || !typeValue.equals("healthAll")) {
			if (StringUtils.isBlank(examUserId)) {
				return super.findAll(requestParams);
			}
			return this.healthInfoService.findAllGroup(Long.valueOf(examUserId));
		}
		String cid = keyMap.get("customerId");
		Long custId = Long.parseLong(cid);
		List<HealthInfo> healthlist = healthInfoService.findHealthAll(custId);
		return healthlist;
	}
}
